package edu.gdkm.demo12;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


public class StudentManager {
    //创建存放Student对象的List，因为需要存放的数据存在多个内容（学号姓名），所以需要先构建Student类用于存放这些内容
    List<Student> studentList=new ArrayList<>();  //List可以使用泛型约束，Student即为其泛型约束，必须使用对象类型,不能基本数据类型

    //初始化List，从facebook_number.txt中读取学生信息，并放入studentList
    public void init() {
        try {
            File file = new File("./facebook_number.txt");
            //使用缓存流实现文件的逐行读取
            BufferedReader br=new BufferedReader(new FileReader(file));
            String info;
            while((info=br.readLine())!=null){
               String infos[]=info.split(",");
               Student student= new Student();
               student.setStudentNumber(infos[0]);
               student.setStudentName(infos[1]);
                student.setPhone(infos[2]);
                studentList.add(student);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //查询所有学生信息
    public void listAll(){
        for(Student student:studentList){
            System.out.println(student);
        }
    }
    //添加学生
    public void addStudent(Student student){
        studentList.add(student);
    }
    //获取学生的位置index
    public int getStudentIndex(Student student){
        return studentList.indexOf(student);
    }
    //获取index位置的学生信息
    public Student getByIndex(int index){
        return studentList.get(index);
    }
    //删除学生信息
    public void delByIndex(int index){
        studentList.remove(index);
    }

    //将List中的数据重新写入facebook_number.txt
    public void outputTxt(){

        try {
            File fileout=new File("./facebook_number.txt");
            BufferedWriter bw=new BufferedWriter(new FileWriter(fileout));
            if(!fileout.exists()){
                fileout.createNewFile();
            }
            for(Student student:studentList){
                bw.write(student.getStudentNumber()+","+student.getStudentName());
                bw.newLine();
            }
            bw.flush();
            bw.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //获取学生人数
    public int getStudentCount(){
        return studentList.size();
    }
    //删除学生信息
    public void delStudent(Student student){
        studentList.remove(student);
    }
    //根据学生的学号查询学生信息
    public Student findByStudentNumber(String studentNumber){
        for(Student student:studentList){
            if(student.getStudentNumber().equals(studentNumber)){
                return student;
            }
        }
        return null;
    }
}
